module;
#include <iostream>
#include <thread>

export module Code_2_1_3;

using namespace std;

class thread_guard {
	std::thread& t;
public:
	explicit thread_guard(std::thread& t_) 
		: t{t_}
	{}
	~thread_guard() {
		if (t.joinable()) {
			t.join();
		}
	}

	thread_guard(thread_guard const&) = delete;
	thread_guard& operator=(thread_guard const&) = delete;
};


struct func {
	int& i;
	func(int& i_) : i{ i_ } {}
	void operator()() {
		for (unsigned j = 0; j < 100000; ++j) {
			do_something(i);
		}
	}
	void do_something(int& i)
	{
		i++;
		cout << "do_something_" << i << endl;
	}
};

export
namespace Code_2_1_3 {
	void run_thread() {
		int some_local_state = 0;
		func my_func(some_local_state);
		std::thread my_thread(my_func);
		thread_guard g(my_thread);
		//while (true) {}

	}
}
